package com.yazi.mxz.common.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;


public class BaseController {
	public static final String REDIRECT_INDEX = "redirect:/";
	public static final String FORWARD_TIP = "tip_fail";
	public static final String TIP_MSG = "tipMsg";
	public static final String TIP_DATA = "tipData";
	

	public Cookie getCookie(String key, HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(key)) {
					return cookie;
				}
			}
		}
		return null;
	}

	public void setCookie(String key, String value, HttpServletResponse response) {
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(Integer.MAX_VALUE);
		cookie.setPath("/");
		if (null == value) {
			cookie.setMaxAge(0);
		}
		response.addCookie(cookie);
	}

	/**
	 * 验证码校验。<br>
	 * session中以‘captcha’为key来记录验证码值，获取该值并与表单值（表单（变量）名也是‘captcha’）进行比较 ，
	 * 比较后销毁session中的值，如果session中的值与表单值一致（忽略大小写），则返回true，否则返回false。
	 * 注意：必须以‘captcha ’作为key将验证码值存储在session中，同时页面提交的验证码表单名也必须为‘captcha’。
	 * 
	 * @return true or false
	 */
	public boolean checkCaptcha(String captcha) {
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		String sessCode = (String) session.getAttribute("captcha");
		session.removeAttribute("captcha");
		if (null == sessCode || null == captcha || !sessCode.equalsIgnoreCase(captcha)) {
			return false;
		}
		return true;
	}
}
